/* eslint-disable no-nested-ternary */
import React from 'react';
import { Input, Button, Icon } from 'antd';
import _ from 'lodash';
import cn from 'classnames';
import styles from './index.less';
import QuickTaskBar from '../QuickTaskBar';
import ChildTaskMore from '../ChildTaskMore';
import ChildTaskMoreSimple from '../ChildTaskMoreSimple';

const { TextArea } = Input;

const ChildTask = ({
    type,
    taskList = [],
    employeeList = [],
    onChange,
    hasMore = false,
    isCheck = false,
    parentEndTime,
    setIsCheck
}) => {
    // console.log('parentEndTime', parentEndTime);
    const [list, setList] = React.useState(taskList);
    // 通过count来强制刷新textarea
    const [count, setCount] = React.useState(0);
    const [visible, setVisible] = React.useState(false);
    const [nowIndex, setNowIndex] = React.useState(0);

    const triggerOnChange = tempList => {
        if (onChange) {
            const arr = tempList.map(item => {
                let { id } = item;
                if (typeof id === 'string' && id.indexOf('temp') !== -1) {
                    id = '';
                }
                return {
                    ...item,
                    id,
                    sourceTaskId: id
                };
            });
            onChange(arr);
        }
    };

    const addTask = () => {
        if (setIsCheck) {
            setIsCheck(false);
        }
        const temp = [
            ...list,
            {
                id: '',
                key: `tempId${new Date().getTime()}`,
                taskName: '',
                executeEmployeeCode: '',
                planStartTime: '',
                planEndTime: parentEndTime || '',
                taskPriority: '',
                auditEmployeeCode: '',
                acceptanceEmployeeCode: ''
            }
        ];
        setList(temp);
        triggerOnChange(temp);
    };

    const arrUpdate = (obj, index) => {
        const arr = [...list];
        arr[index] = {
            ...arr[index],
            ...obj
        };
        setList(arr);
        triggerOnChange(arr);
    };

    const arrUpdateDebounce = _.debounce((obj, index) => {
        arrUpdate(obj, index);
    }, 100);

    const handleTaskChange = (val, index) => {
        arrUpdate(val, index);
    };

    const handleInputChange = (e, index) => {
        arrUpdateDebounce(
            {
                taskName: e.target.value.trim()
            },
            index
        );
    };

    const handleDelete = index => {
        const arr = list.concat();
        arr.splice(index, 1);
        setList(arr);
        triggerOnChange(arr);
    };

    const handleOpenMore = index => {
        // console.log(index);
        setNowIndex(index);
        setVisible(!visible);
    };

    const handleMoreOk = item => {
        // console.log('item', item);
        arrUpdate(item, nowIndex);
        const cnt = count + 1;
        setCount(cnt);
    };

    React.useEffect(() => {
        setList(taskList);
    }, [taskList]);

    return (
        <div className={styles.childTask}>
            <div className={styles.childTitle}>
                <div>
                    <i className="icon iconfont iconzirenwu" style={{ fontSize: 14 }}></i>&nbsp;子任务
                </div>
                <Button type="link" onClick={addTask}>
                    +增加子任务
                </Button>
            </div>
            {list.map((item, index) => (
                <div
                    className={cn(styles.taskItem, { [styles.isCheck]: isCheck && !item.taskName.trim() })}
                    key={item.id || item.key}
                >
                    {count % 2 === 0 && (
                        <TextArea
                            maxLength={200}
                            placeholder="请输入任务名称"
                            autosize={{ maxRows: 5 }}
                            defaultValue={item.taskName}
                            onChange={e => handleInputChange(e, index)}
                        />
                    )}
                    {count % 2 === 1 && (
                        <TextArea
                            maxLength={200}
                            placeholder="请输入任务名称"
                            autosize={{ maxRows: 5 }}
                            defaultValue={item.taskName}
                            onChange={e => handleInputChange(e, index)}
                        />
                    )}
                    <QuickTaskBar
                        size="mini"
                        employeeList={employeeList}
                        isCheck={isCheck}
                        executeEmployeeCode={item.executeEmployeeCode}
                        planStartTime={item.planStartTime}
                        planEndTime={item.planEndTime}
                        taskPriority={item.taskPriority}
                        auditEmployeeCode={item.auditEmployeeCode}
                        acceptanceEmployeeCode={item.acceptanceEmployeeCode}
                        onChange={e => handleTaskChange(e, index)}
                        taskType={type}
                        // parentEndTime={parentEndTime}
                        acceptanceStatus={item.acceptanceStatus || undefined}
                        taskStatus={item.taskStatus || undefined}
                    />
                    <Icon
                        type="more"
                        title="更多"
                        rotate={90}
                        style={{ marginRight: 12, cursor: 'pointer', fontSize: 16, color: '#333333' }}
                        onClick={() => handleOpenMore(index)}
                    />
                    <i
                        className="icon iconfont iconshanchu"
                        style={{ marginRight: 12, cursor: 'pointer', color: '#333333' }}
                        title="删除"
                        onClick={() => handleDelete(index)}
                    />
                </div>
            ))}
            {hasMore && (
                <ChildTaskMore
                    taskDetail={(list && list[nowIndex]) || null}
                    // parentEndTime={parentEndTime}
                    visible={visible}
                    setVisible={setVisible}
                    onOk={handleMoreOk}
                />
            )}
            {!hasMore && (
                <ChildTaskMoreSimple
                    taskDetail={(list && list[nowIndex]) || null}
                    visible={visible}
                    setVisible={setVisible}
                    onOk={handleMoreOk}
                />
            )}
        </div>
    );
};

export default ChildTask;
